package cn.xuexiluxian.open.framework.security.filter;

import cn.xuexiluxian.open.common.constant.Constants;
import cn.xuexiluxian.open.common.utils.AesUtil;
import cn.xuexiluxian.open.framework.security.MobileAuthenticationToken;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MobileCaptchaAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    private String mobileParameter = "mobile";
    private boolean postOnly = true;

    public MobileCaptchaAuthenticationFilter() {
        super(new AntPathRequestMatcher(Constants.MOBILE_LOGIN_URL, "POST"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) {
        if (postOnly && !"post".equalsIgnoreCase(request.getMethod())) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        // 从请求中获取手机号，来验证手机号是否有效
        String mobile = request.getParameter("mobile");
        if (mobile == null) {
            mobile = "";
        }
        mobile = mobile.trim();

        try {
            mobile = AesUtil.decrypt(mobile);
        } catch (Exception ignored) {
        }

        MobileAuthenticationToken authRequest = new MobileAuthenticationToken(mobile);

        setDetails(request, authRequest);

        return this.getAuthenticationManager().authenticate(authRequest);
    }

    /**
     * 将请求中的 sessionID 和 host 主机ip放到 MobileAuthenticationToken
     * set
     */
    protected void setDetails(HttpServletRequest request, MobileAuthenticationToken authRequest) {
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
    }

    public void setPostOnly(boolean postOnly) {
        this.postOnly = postOnly;
    }

    public String getMobileParameter() {
        return mobileParameter;
    }

    public void setMobileParameter(String mobileParameter) {
        this.mobileParameter = mobileParameter;
    }
}
